#!/usr/bin/python
# -*- encoding: utf-8 -*-

#   MusicLog Daemon
#
#   Copyright (c) 2008 Rafael G. Martins <rafael@rafaelmartins.com>
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.

from os import fork, kill, access, W_OK, remove, path
from sys import argv, exit
from signal import SIGKILL
from commands import getoutput
from musiclog import MusicLog

class MusicLogDaemon:
  
  pid_file = "/var/run/musiclog.pid"
  
  def __init__(self):
    if len(argv) >= 4:
      if access(path.dirname(self.pid_file), W_OK) == False:
        exit("You don't have permissions to run MusicLog!")
      if path.exists(self.pid_file) == True and self._is_running() == True:
        exit("MusicLog is already running...")
  
  def _is_running(self):
    is_running = int(getoutput('pidof -x %s | wc -w' % argv[0]))
    return is_running > 1
  
  def _parent(self, pid):
    pid_f = open(self.pid_file, "w")
    pid_f.write(str(pid))
    pid_f.close()
    print "MusicLog Daemon started..."
    exit(0)
  
  def _children(self):
    if len(argv) == 5:
      password = argv[4]
    else:
      password = None
    mus = MusicLog(argv[1], int(argv[2]), argv[3], password)
    mus.update()
    mus.close()
    exit(0)

  def start(self):
    pid = fork()
    if pid != 0:
      self._parent(pid)
    else:
      self._children()

  def stop(self):
    if path.exists(self.pid_file) == True:
      pid = int(file(self.pid_file).read())
      if pid != 0:
        try:
          kill(pid, SIGKILL)
          remove(self.pid_file)
          print "MusicLog Daemon stopped..."
        except:
          exit("Failed to kill the process of MusicLog...")
    else:
      exit("MusicLog isn't started yet...")
